package com.controller;

import com.bean.User;
import com.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.ui.Model;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpSession;

@SessionAttributes("session")                //也可以调用Java Servlet API jar包，用法和model差不多，HttpSession session
@Controller
@ContextConfiguration("classpath:springmvc.xml")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login")
    public String login(Model model, User user, HttpSession session) {//用Java Servlet API jar包 利用HttpSession session设置
        User user1 = userMapper.findUser(user);
        if (user1 != null) {
            model.addAttribute("msg", "登录成功" + user.getUsername());//model可以直接加用户名!!
            model.addAttribute("session", "这是利用@SessionAttribute获取的ssession里的值");  //先将值传入session，@SessionAttributes("session")可以随时取
            session.setAttribute("session2", "这是利用Java Servlet API jar包获取的ssession里的值");
            return "main";
        } else {
            model.addAttribute("msg", "登录失败");
            return "index";
        }
    }

    @RequestMapping("/tosession")
    public String session() {
        return "session";
    }

    @RequestMapping("/tosession2")
    public String session2(Model model, HttpSession session) {
        String str = (String) session.getAttribute("session2");
        model.addAttribute("msg", str);
        return "session2";
    }
}
